<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>02_优先级队列</title>
  </head>
  <body>
    <script>
      //封装优先级队列
      function PrioritizeQueue(){
          //封装属性
          this.items = [];
          function QueueElement(element,priority){
              this.element = element;
              this.priority = priority;
          }

          //插入方法
          PrioritizeQueue.prototype.enqueue = function(element,priority){
              //1、创建QueueElement对象
              var queueElement=new QueueElement(element,priority)
              //2、判断队列是否为空
              if(this.items.length===0){
                  this.items.push(queueElement)
              }else{
                  var added=false
                  for (var i = 0; i < this.items.length; i++) {
                      if(queueElement.priority<this.items[i].priority){
                          this.items.splice(i,0,queueElement)
                          added=true;
                          break;
                      }
                  }
                  if(!added){
                      this.items.push(queueElement)
                  }
              }
          }
           //查看前端元素
           PrioritizeQueue.prototype.front=function(){
              return this.items[0];
          }
          //2、从队列删除前端元素
          PrioritizeQueue.prototype.dequeue = function(){
              return this.items.shift();
          }
          //3、查看是否为空
          PrioritizeQueue.prototype.isEmpty = function(){
              return this.items.length == 0;
          }
          //4、查看元素个数
          PrioritizeQueue.prototype.size = function(){
              return this.items.length;
          }
          //5、tostring()
          PrioritizeQueue.prototype.tostring = function(){
              var str = ''
              for(var i=0;i<this.items.length;i++) {
                  str+=this.items[i].element+'-'+this.items[i].priority+'';
              }
              return str;
          }
      }
      var pq=new PrioritizeQueue();
      pq.enqueue('AAA',10)
      pq.enqueue('BBB',22)
      pq.enqueue('ccc',56)
      pq.enqueue('DDD',800)
      pq.enqueue('EEE',2)
      console.log('pq',pq)
    </script>
  </body>
</html>
